package com.zjm.xml;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.junit.Test;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author ZJM
 * @date 2024/4/7 21:53
 */
public class Dom4jTest01 {

    @Test
    public void test1() {
        SAXReader reader = new SAXReader();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            // 读取XML文件
            Document document = reader.read("src/main/resources/xml/book.xml");
            // 获取根元素
            Element root = document.getRootElement();
            // 获取所有书籍元素    通过标签名获取子元素
            List<Element> bookElements = root.elements("book");
            // 遍历每本书
            for (Element bookElement : bookElements) {
                // System.out.println("Book ID: " + bookElement.attributeValue("id"));
                // System.out.println("Title: " + bookElement.elementText("title"));
                // System.out.println("Author: " + bookElement.elementText("author"));
                // System.out.println("Genre: " + bookElement.elementText("genre"));
                // System.out.println("Price: " + bookElement.elementText("price"));
                // System.out.println("Publish Date: " + bookElement.elementText("publish_date"));
                // System.out.println();
                String id = bookElement.attributeValue("id");
                String title = bookElement.elementText("title");
                String author = bookElement.elementText("author");
                String genre = bookElement.elementText("genre");
                String price = bookElement.elementText("price");
                String publish_date = bookElement.elementText("publish_date");
                Book book = new Book(id, title, author, genre, new BigDecimal(price), dateFormat.parse(publish_date));
                System.out.println(book);
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}
